package com.newtouch.bxzs.business.train.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.business.enclosure.mapper.AttachmentMapper;
import com.newtouch.bxzs.business.enclosure.service.AttachmentService;
import com.newtouch.bxzs.business.train.controller.KnowledgeCardController;
import com.newtouch.bxzs.business.train.mapper.KnowledgeCardMapper;
import com.newtouch.bxzs.business.train.model.bo.KnowledgeCardAppBO;
import com.newtouch.bxzs.business.train.model.bo.KnowledgeCardBO;
import com.newtouch.bxzs.business.train.model.vo.KnowledgeCardAppVO;
import com.newtouch.bxzs.business.train.model.vo.NewKnowledgeCardVO;
import com.newtouch.bxzs.business.train.service.KnowledgeCardService;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.em.ButtonTypeEnum;
import com.newtouch.bxzs.common.base.em.PublishStatusEnum;
import com.newtouch.bxzs.common.base.model.Attachment;
import com.newtouch.bxzs.common.base.model.KnowledgeCard;
import com.newtouch.bxzs.common.base.model.vo.EnclosureVO;
import com.newtouch.bxzs.common.base.util.CheckPublishDateUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 知识小灵通业务逻辑实现层
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/1/6 13:40</td>
 * <td>lingshouyi</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author lingshouyi
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class KnowledgeCardServiceImpl implements KnowledgeCardService {

    @Autowired
    private KnowledgeCardMapper knowledgeCardMapper;

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private AttachmentMapper attachmentMapper;

    /**
     * 获取配置的知识小灵通的发布时间的最大限制
     */
    @Value("${publishTimeConfig.maxPublishTime}")
    private Integer maxPublishTime;

    /**
     * 获取配置的广告的撤销时间的最大限制
     */
    @Value("${revokeTimeConfig.maxRevokeTime}")
    private String maxRevokeTime;

    /**
     * 已发布状态码常量
     */
    private static final String PUBLISHED_STATUS = PublishStatusEnum.PUBLISHED_STATUS.getResultCode();
    /**
     * 未发布状态码常量
     */
    private static final String UNPUBLISHED_STATUS = PublishStatusEnum.UNPUBLISH_STATUS.getResultCode();
    /**
     * 撤销状态码常量
     */
    private static final String REVOKED_STATUS = PublishStatusEnum.REVOKED_STATUS.getResultCode();

    /**
     * 静态变量：系统日志
     */
    private static final Log logger = LogFactory.getLog(KnowledgeCardController.class);

    /**
     * 知识卡片通知条数
     */
    private static final Integer NUMBER = 5;

    @Override
    public List<KnowledgeCardAppBO> getKnowledgeCardNoticeList() {
        return knowledgeCardMapper.getKnowledgeCardNoticeList(NUMBER);
    }

    @Override
    public IPage<KnowledgeCardAppBO> getKnowledgeCardList(KnowledgeCardAppVO knowledgeCardAppVO, Boolean flag) {
        /* 判断是否为空 */
        if (BeanUtil.isEmpty(knowledgeCardAppVO)) {
            return null;
        }
        /* 分页参数 */
        Page<KnowledgeCardAppBO> page = new Page<>(knowledgeCardAppVO.getCurrentPage(), knowledgeCardAppVO.getPageSize());
        QueryWrapper<KnowledgeCard> qw = new QueryWrapper<>();
        /*当前登录用户id*/
        String createUserId = null;
        if (flag) {
            knowledgeCardAppVO.setPublishStatus(PUBLISHED_STATUS);
            qw.eq("PUBLISH_STATUS", PUBLISHED_STATUS);
        } else {
            createUserId = Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId();
        }
        /* 知识卡片列表信息 */
        IPage<KnowledgeCardAppBO> knowledgeCardList = knowledgeCardMapper.getKnowledgeCardList(
                createUserId,
                knowledgeCardAppVO.getKnowledgeCardTitle(),
                knowledgeCardAppVO.getKnowledgeCardType(),
                knowledgeCardAppVO.getPublishStatus(), page);
        if (CollectionUtils.isEmpty(knowledgeCardList.getRecords())) {
            return null;
        }
        return knowledgeCardList;
    }

    @Override
    public KnowledgeCardBO getKnowledgeCardDetail(String knowledgeCardId) {
        /* 判断是否为空 */
        if (StringUtils.isEmpty(knowledgeCardId)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        /* 创建一个详情BO */
        KnowledgeCardBO knowledgeCardBO = new KnowledgeCardBO();
        /* 将源数据copy到BO */
        BeanUtil.copyProperties(knowledgeCardMapper.selectById(knowledgeCardId), knowledgeCardBO);
        /* 构造条件 */
        HashMap<String, List<String>> result = attachmentService
                .getEnclosureList(new EnclosureVO(knowledgeCardId, null));
        if (result != null) {
            knowledgeCardBO.setAttachments(result);
        }
        logger.info("查看知识卡片详情");
        return knowledgeCardBO;
    }

    @Override
    public String modifyKnowledgeCard(NewKnowledgeCardVO newKnowledgeCardVO) {
        if (BeanUtil.isEmpty(newKnowledgeCardVO)) {
            return null;
        }
        KnowledgeCard knowledgeCard = new KnowledgeCard();
        BeanUtil.copyProperties(newKnowledgeCardVO, knowledgeCard);
        /* 校验必填项 */
        if (StringUtils.isEmpty(knowledgeCard.getKnowledgeCardTitle())
                || StringUtils.isEmpty(knowledgeCard.getKnowledgeCardType())
                || StringUtils.isEmpty(knowledgeCard.getKnowledgeCardContent())) {
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
        /* 效验发布时间和撤销时间是否正确 */
        if (newKnowledgeCardVO.getRevokeTime() != null || newKnowledgeCardVO.getPublishTime() != null) {
            /* 检验发布撤销时间 */
            CheckPublishDateUtils.checkDate(newKnowledgeCardVO.getPublishTime(), newKnowledgeCardVO.getRevokeTime(),
                    maxPublishTime, maxRevokeTime);
        }
        /* 当传入知识卡片id为空时,新增 */
        if (StringUtils.isEmpty(newKnowledgeCardVO.getKnowledgeCardId())) {
            knowledgeCard.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            knowledgeCard.setCreateTime(new Date());
            knowledgeCard.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            knowledgeCard.setUpdateTime(new Date());
            /* 传入的按钮类型 */
            sendOrTemporary(newKnowledgeCardVO.getButtonType(), knowledgeCard);
            knowledgeCardMapper.insert(knowledgeCard);
            logger.info("新增成功");
        } else {
            /* 修改状态 */
            knowledgeCard.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            knowledgeCard.setUpdateTime(new Date());
            /* 传入的按钮类型 */
            sendOrTemporary(newKnowledgeCardVO.getButtonType(), knowledgeCard);
            QueryWrapper<KnowledgeCard> qw = new QueryWrapper<>();
            qw.eq("KNOWLEDGE_CARD_ID", newKnowledgeCardVO.getKnowledgeCardId());
            knowledgeCardMapper.update(knowledgeCard, qw);
            logger.info("修改成功");
        }
        /* 返回当前知识卡片ID */
        return knowledgeCard.getKnowledgeCardId();
    }

    @Override
    public Integer changeKnowledgeCardState(String knowledgeCardId, String publishStatus) {
        if (StringUtils.isEmpty(knowledgeCardId)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        QueryWrapper<KnowledgeCard> qw = new QueryWrapper<>();
        qw.eq("KNOWLEDGE_CARD_ID", knowledgeCardId);
        KnowledgeCard knowledgeCard = knowledgeCardMapper.selectOne(qw);
        /* 如果为撤销，则设置撤销时间 */
        if (REVOKED_STATUS.equals(publishStatus)) {
            knowledgeCard.setRevokeTime(new Date());
        }
        /* 如果为发布，则设置发布时间 */
        if (PUBLISHED_STATUS.equals(publishStatus)) {
            knowledgeCard.setPublishTime(new Date());
        }
        /* 设置发布状态，修改人，和修改时间 */
        knowledgeCard.setPublishStatus(publishStatus);
        knowledgeCard.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        knowledgeCard.setUpdateTime(new Date());
        return knowledgeCardMapper.update(knowledgeCard, qw);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteKnowledgeCard(List<String> knowledgeCardIds) {
        /* 判断知识小灵通ID集合是否为空 */
        if (CollectionUtils.isEmpty(knowledgeCardIds)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        /* 判断ID集合是否存在空字符串,如果有就移除. */
        for (String knowledgeCardId : knowledgeCardIds) {
            if (StringUtils.isEmpty(knowledgeCardId)) {
                knowledgeCardIds.remove(knowledgeCardId);
            }
        }
        /* 判断勾选中的知识卡片是否存在已发布的 */
        QueryWrapper<KnowledgeCard> qw = new QueryWrapper<>();
        qw.in("KNOWLEDGE_CARD_ID", knowledgeCardIds)
                .eq("PUBLISH_STATUS", PUBLISHED_STATUS);
        List<KnowledgeCard> knowledgeCardList = knowledgeCardMapper.selectList(qw);
        if (CollectionUtils.isEmpty(knowledgeCardList)) {
            /*知识小灵通删除成功后,删除附件*/
            if (knowledgeCardMapper.deleteBatchIds(knowledgeCardIds) > 0) {
                return attachmentMapper.delete(new QueryWrapper<Attachment>().in("ATTACHMENT_RELATION_ID", knowledgeCardIds));
            }
            logger.info("删除成功");
        } else {
            throw new BaseException(BaseErrorEnum.PUBLISH_STATUS);
        }
        return null;
    }

    /**
     * 发布/暂存
     *
     * @param buttonType    按钮类型
     * @param knowledgeCard 知识卡片实体
     */
    private void sendOrTemporary(String buttonType, KnowledgeCard knowledgeCard) {
        /* 点击发布按钮 */
        if (buttonType.equals(ButtonTypeEnum.PUBLIC_BUTTON.getCode())) {
            /* 设置为已发布状态 */
            knowledgeCard.setPublishStatus(PUBLISHED_STATUS);
            knowledgeCard.setPublishTime(new Date());
        }
        /* 点击暂存按钮 */
        if (buttonType.equals(ButtonTypeEnum.TEMPORARY_BUTTON.getCode())) {
            /* 设置状态为未发布状态 */
            knowledgeCard.setPublishStatus(UNPUBLISHED_STATUS);
        }

    }

}
